package com.liu.voluntary.controller;


import com.liu.voluntary.mapper.ActivityMapper;
import com.liu.voluntary.mapper.AdminMapper;
import com.liu.voluntary.pojo.Activity;
import com.liu.voluntary.pojo.Admin;
import com.liu.voluntary.pojo.User;
import com.liu.voluntary.service.AdminService;

import com.liu.voluntary.util.SearchHttpAK;
import com.liu.voluntary.service.UserService;
import com.liu.voluntary.util.ActivityUtils;

import com.liu.voluntary.util.SexJson;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.liu.voluntary.service.ActivityService;

@Controller
public class ActivityController {

    @Resource
    private ActivityMapper activityMapper;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private UserService userService;

    @Resource
    private AdminService adminService;

    @Resource
    private ThymeleafViewResolver thymeleafViewResolver;

    @Resource
    private ActivityService activityService;

//    @RequestMapping("/toActivityList")
//    @ResponseBody
//    public String toActivityList(@CookieValue("Ticket") String Ticket, Model model, HttpServletRequest request, HttpServletResponse response) {
//
//        List<Activity> activities = activityMapper.selectList(null);
//        //先到redis获取页面
//        ValueOperations valueOperations = redisTemplate.opsForValue();
//        String html = (String) valueOperations.get("activityList");
//        //如果redis里面有所需页面
//        if (StringUtils.hasText(html)) {
//            return html;
//        }
//
////        管理员和用户都走这个controller 进行活动查询 所以只要有一个不为空就证明登陆过了，只是身份不一样
//        User user = userService.getUserInRedis(Ticket, request, response);
//        Admin admin = adminService.getAdminInRedis(Ticket, request, response);
//
//        if (user == null && admin == null) {
//            return "login";
//        }
//
//        String role = "";
//
//        if (user != null){
//            role = "user";
//        }
//
//        if (admin != null){
//            role = "admin";
//        }
//
//        model.addAttribute("role",role);
//
////        0:未开始 1:进行中 2:已结束
//
//        for (Activity activity : activities) {
//            Date startTime = activity.getStartTime();
//            Date endTime = ActivityUtils.calculateEndTime(activity);
//            Date now = new Date();
//
//            //还未开始
//            if (now.before(startTime)) {
//                activity.setActivityState(0);
//            } else if (now.after(endTime)) {
//                activity.setActivityState(2);
//            } else {
//                activity.setActivityState(1);
//            }
//
//        }
//        model.addAttribute("activities", activities);
//
//        //如果redis里没有所需要的页面    手动渲染，并存入redis
//        WebContext webContext = new WebContext(request, response, request.getServletContext(),
//                request.getLocale(), model.asMap());
//
//
//        html = thymeleafViewResolver.getTemplateEngine().process("activityList", webContext);
//
//        if (StringUtils.hasText(html)) {     //将页面放到redis，并每60s更新一次
//            valueOperations.set("activityList", html, 1, TimeUnit.SECONDS);
//        }
//
//        return html;
//    }




//    @RequestMapping("/toActivityList")
//    public String toActivityList(@CookieValue("Ticket") String Ticket, Model model, HttpServletRequest request, HttpServletResponse response) {
//
//        List<Activity> activities = activityMapper.selectList(null);
//
////        管理员和用户都走这个controller 进行活动查询 所以只要有一个不为空就证明登陆过了，只是身份不一样
//        User user = userService.getUserInRedis(Ticket, request, response);
//        Admin admin = adminService.getAdminInRedis(Ticket, request, response);
//
//        if (user == null && admin == null) {
//            return "login";
//        }
//
//        String role = "admin";
//
//        if (user != null){
//            role = "user";
//        }
//
//
//        model.addAttribute("role",role);
//
////        活动
////        0:未开始 1:进行中 2:已结束
//
//        for (Activity activity : activities) {
//            Date startTime = activity.getStartTime();
//            Date endTime = ActivityUtils.calculateEndTime(activity);
//            Date now = new Date();
//
//            //活动还未开始
//            if (now.before(startTime)) {
//                activity.setActivityState(0);
//            } else if (now.after(endTime)) {
//                activity.setActivityState(2);
//            } else {
//                activity.setActivityState(1);
//            }
//
//        }
//
//
////        报名
////        0:未开始 1:进行中 2:已结束
//        for (Activity activity : activities) {
//            Date enlistsStart = activity.getEnlistsStart();
//            Date enlistsEnd = activity.getEnlistsEnd();
//            Date now = new Date();
//
//            //报名还未开始
//            if (now.before(enlistsStart)) {
//                activity.setEnlistsState(0);
//            } else if (now.after(enlistsEnd)) {
//                activity.setEnlistsState(2);
//            } else {
//                activity.setEnlistsState(1);
//            }
//
//        }
//
//        model.addAttribute("activities", activities);
//
//
//        return "activityList";
//    }




    @RequestMapping("/toActivityDetail/{id}")
    public String toActivityDetail(@CookieValue("Ticket") String Ticket,@PathVariable(value = "id") String id, Model model,HttpServletRequest request, HttpServletResponse response) {

        Activity activity = activityMapper.selectById(id);
        if (activity == null) {
            model.addAttribute("msg", "查看错误");
            return "activityList";
        }

        //        管理员和用户都走这个controller 进行活动查询 所以只要有一个不为空就证明登陆过了，只是身份不一样
        User user = userService.getUserInRedis(Ticket, request, response);
        Admin admin = adminService.getAdminInRedis(Ticket, request, response);

        //如果登录的是管理员，则后端判断
        if (admin != null){
            model.addAttribute("admin",admin);
        }


        int remainStartSeconds;       //距离秒杀开始时间   >0 未开始  0:秒杀进行中  -1:秒杀已经结束

        Date startTime = activity.getStartTime();
        Date endTime = ActivityUtils.calculateEndTime(activity);
        Date now = new Date();

        //还未开始
        if (now.before(startTime)) {
            activity.setActivityState(0);
            remainStartSeconds = (int) ((startTime.getTime() - now.getTime()) / 1000);
        } else if (now.after(endTime)) {
            activity.setActivityState(2);
            remainStartSeconds = -1;

        } else {
            activity.setActivityState(1);
            remainStartSeconds = 0;
        }


        Date enlistsStart = activity.getEnlistsStart();      //报名开始时间
        Date enlistsEnd = activity.getEnlistsEnd();          //报名结束时间
        int remainEnlistsSeconds;
        //还未开始
        if (now.before(enlistsStart)) {
            activity.setEnlistsState(0);
            remainEnlistsSeconds = (int) ((enlistsStart.getTime() - now.getTime()) / 1000);
        } else if (now.after(enlistsEnd)) {
            activity.setEnlistsState(2);
            remainEnlistsSeconds = -1;

        } else {
            activity.setEnlistsState(1);
            remainEnlistsSeconds = 0;
        }


        model.addAttribute("remainStartSeconds", remainStartSeconds);
        model.addAttribute("remainEnlistsSeconds", remainEnlistsSeconds);
        model.addAttribute("activity", activity);

        return "activityDetail";
    }


    @RequestMapping("/toDeleteActivity/{id}")
    public String toDeleteActivity(@PathVariable(value = "id") String id, Model model) {

        Activity activity = activityMapper.selectById(id);
        if (activity == null) {
            model.addAttribute("msg", "查看错误");
            return "activityList";
        }
        int i = activityMapper.deleteById(id);
        if (i == 0) {
            model.addAttribute("msg", "删除失败");
        }


        return "redirect:/activityList";
    }


    @RequestMapping("/toAddActivityPage")
    public String toAddActivityPage() {

        return "addActivity";
    }


    @Resource
    private AdminMapper adminMapper;
    @RequestMapping("/toAddActivity")
    public String toAddActivity(@RequestParam(value = "activityName") String activityName,
                                @RequestParam(value = "activityAddress") String activityAddress,
                                @RequestParam(value = "startTime") @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm") Date startTime,
                                @RequestParam(value = "sustain") int sustain,
                                @RequestParam(value = "number") int number,
                                @RequestParam(value = "enlistsStart") @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm") Date enlistsStart,
                                @RequestParam(value = "enlistsEnd") @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm") Date enlistsEnd,
                                @RequestParam(value = "introduce") String introduce,
                                Model model, HttpServletRequest request,
                                @CookieValue("Ticket") String Ticket) throws Exception {


        Activity activity = new Activity();
        activity.setActivityName(activityName);
        activity.setActivityAddress(activityAddress);

        String info = SearchHttpAK.getGeocodingInfo(activityAddress);

        String s = SexJson.sexJsonToNum(info);

        String[] split = s.split(",");
        activity.setLng(Double.valueOf(split[0]));
        activity.setLat(Double.valueOf(split[1]));

//        BaiduGeoCodingService.Location location = BaiduGeoCodingService.getLocationFromAddress(activityAddress);
//        if (location != null) {
//            activity.setLat(location.getLat());
//            activity.setLng(location.getLng());
//        }



        activity.setStartTime(startTime);
        activity.setSustain(sustain);
        activity.setNumber(number);
        activity.setEnlistsStart(enlistsStart);
        activity.setEnlistsEnd(enlistsEnd);
        activity.setIntroduce(introduce);

        int i = activityMapper.insert(activity);
        if (i == 0) {
            model.addAttribute("msg", "插入失败，请重试");
            return "redirect:/toAddActivityPage";
        }

        // 更新管理员发布活动次数
        Admin admin = (Admin) redisTemplate.opsForValue().get("admin:"+Ticket);
        if (admin != null) {

            admin.setPublish(admin.getPublish() + 1);
            adminMapper.updateById(admin);

            // 确保更新后的对象被存回到 Redis
            redisTemplate.opsForValue().set("admin:"+Ticket,admin);
        }

        return "superAdmin";
    }

    @RequestMapping("/toActivityList")
    public String activityList(@CookieValue("Ticket") String Ticket, Model model, 
            @RequestParam(defaultValue = "1") Integer page, 
            @RequestParam(defaultValue = "6") Integer size,
            HttpServletRequest request, HttpServletResponse response) {
        
        // 检查用户登录状态
        User user = userService.getUserInRedis(Ticket, request, response);
        Admin admin = adminService.getAdminInRedis(Ticket, request, response);
        if (user == null && admin == null) {
            return "login";
        }

        // 设置用户角色
        String role = user != null ? "user" : "admin";
        model.addAttribute("role", role);

        // 创建分页对象
        Page<Activity> pageParam = new Page<>(page, size);
        
        // 执行分页查询
        Page<Activity> activityPage = activityService.page(pageParam);
        List<Activity> activities = activityPage.getRecords();
        
        // 计算活动状态
        Date now = new Date();
        for (Activity activity : activities) {
            // 计算活动状态
            Date startTime = activity.getStartTime();
            Date endTime = ActivityUtils.calculateEndTime(activity);
            
            if (now.before(startTime)) {
                activity.setActivityState(0);
            } else if (now.after(endTime)) {
                activity.setActivityState(2);
            } else {
                activity.setActivityState(1);
            }

            // 计算报名状态
            Date enlistsStart = activity.getEnlistsStart();
            Date enlistsEnd = activity.getEnlistsEnd();
            
            if (now.before(enlistsStart)) {
                activity.setEnlistsState(0);
            } else if (now.after(enlistsEnd)) {
                activity.setEnlistsState(2);
            } else {
                activity.setEnlistsState(1);
            }
        }
        
        // 将分页结果添加到模型中
        model.addAttribute("activities", activities);
        model.addAttribute("currentPage", activityPage.getCurrent());
        model.addAttribute("totalPages", activityPage.getPages());
        model.addAttribute("totalItems", activityPage.getTotal());
        model.addAttribute("pageSize", size);
        
        return "activityList";
    }

}



